package com.zjs.vueRole.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjs.vueMenu.entity.VueMenu;
import com.zjs.vueMenu.service.VueMenuService;
import com.zjs.vueRole.entity.VueRole;
import com.zjs.vueRole.mapper.VueRoleMapper;
import com.zjs.vueRole.service.VueRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zjs
 * @since 2020-07-06
 */
@Service
public class VueRoleServiceImpl extends ServiceImpl<VueRoleMapper, VueRole> implements VueRoleService {


    @Autowired
    private VueMenuService vueMenuService;

    @Override
    public VueRole getRoleMenuById(Long id) {
        VueRole role = baseMapper.selectById(id);
        List<VueMenu> menu = baseMapper.getRoleMenuById(id);
        //将菜单分等级嵌套
        List<VueMenu> twoIncludeThree = menu.stream().filter(item -> item.getPid() != 0).peek(
                item -> item.setItems(getMenus(item, menu))
        ).collect(Collectors.toList());

        List<VueMenu> collect = menu.stream().filter(item -> item.getPid() == 0).peek(
                item -> item.setItems(getMenus(item, twoIncludeThree))
        ).collect(Collectors.toList());

        role.setItems(collect);
        return role;
    }

    @Override
    public List<VueMenu> getAllMenus() {
        List<VueMenu> menu = vueMenuService.list(null);

        List<VueMenu> twoIncludeThree = menu.stream().filter(item -> item.getPid() != 0).peek(
                item -> item.setItems(getMenus(item, menu))
        ).collect(Collectors.toList());

        List<VueMenu> collect = menu.stream().filter(item -> item.getPid() == 0).peek(
                item -> item.setItems(getMenus(item, twoIncludeThree))
        ).collect(Collectors.toList());

        return collect;
    }

    @Override
    @Transactional
    public void updateRoleMenus(Long id, String menuIds) {
        try {
            //删除改角色id原有菜单(删除关联表信息)
            baseMapper.deleteByRoleId(id);
            //保存新的关联信息
            String[] menus = menuIds.split(",");
            baseMapper.saveRoleMenus(id,menus);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    public List<VueMenu> getMenus(VueMenu m, List<VueMenu> list) {
        return list.stream().filter(item -> item.getPid().equals(m.getId()))
                .collect(Collectors.toList());
    }
}
